package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.UserDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.vo.MemberVo;
import com.zzyl.nursing.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 家属老人中间Service业务层处理
 *
 * @author alexis
 * @date 2025-06-06
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 绑定家人
     *
     * @param userDto 家人信息
     */
    @Override
    public void add(UserDto userDto) {
        // 1.判断是否登录小程序
        // 获取用户信息
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录小程序");
        }

        // 2.小程序端输入信息绑定
        // 3.查看信息是否为空
        if (ObjectUtil.isEmpty(userDto)) {
            throw new BaseException("绑定内容不能为空");
        }

        // 简化判断逻辑，从入住表中查询
        CheckIn checkIn = checkInService.lambdaQuery().eq(CheckIn::getIdCardNo, userDto.getIdCard()).eq(
                CheckIn::getElderName,
                userDto.getName()
                                                                                                       ).eq(
                CheckIn::getStatus
                , 0
                                                                                                           ).one();
        if (ObjectUtil.isEmpty(checkIn)) {
            throw new BaseException("未查询到入住信息，该老人未入住");
        }

        // 4.判断是否绑定过此家人
        Long count =
                lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId)
                             .eq(FamilyMemberElder::getElderId, checkIn.getElderId()).count();
        if (count > 0) {
            throw new BaseException("此家人已绑定过此老人");
        }

        // 5.绑定成功，保存信息
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(checkIn.getElderId());
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(userDto.getRemark());
        save(familyMemberElder);
    }


    /**
     * 解绑老人
     *
     * @param mid 家属老人中间表id
     */
    @Override
    public void handleUnbind(Long mid) {
        removeById(mid);
    }

    /**
     * 获取家人信息
     */
    @Override
    public List<UserVo> my() {
        // 1.获取当前登录用户id
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("用户未登录");
        }

        // 2.根据用户id查询家人信息
        List<FamilyMemberElder> familyMemberElders = lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId)
                                                                  .list();

        List<UserVo> userVos = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(familyMemberElders)) {
            // 收集所有老人ID
            List<Long> elderIds = familyMemberElders.stream()
                                                    .map(FamilyMemberElder::getElderId)
                                                    .collect(Collectors.toList());

            // 批量查询老人信息并构建Map
            Map<Long, String> elderMap = elderMapper.selectBatchIds(elderIds)
                                                    .stream()
                                                    .collect(Collectors.toMap(Elder::getId, Elder::getName));

            // 转换为UserVo
            familyMemberElders.forEach(fme -> {
                UserVo userVo = BeanUtil.copyProperties(fme, UserVo.class);
                String name = elderMap.get(fme.getElderId());
                if (name != null) {
                    userVo.setElderName(name);
                }
                userVos.add(userVo);
            });
        }
        // 3.返回
        return userVos;
    }

    /**
     * 获取家人列表简单写法
     *
     * @return 家人列表
     */
    @Override
    public List<UserVo> getUserVoList() {
        Long userId = UserThreadLocal.getUserId();
        return familyMemberElderMapper.getUserVoList(userId);
    }

    /**
     * 获取家人列表(分页）
     *
     * @return 家人列表
     */
    @Override
    public List<MemberVo> listByPage() {
        List<MemberVo> memberVoList = new ArrayList<>();

        // 1.获取当前登录用户id
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("用户未登录");
        }

        // 2.根据用户id查询家人信息
        List<FamilyMemberElder> familyMemberElders =
                lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId).list();
        if (ObjectUtil.isEmpty(familyMemberElders)) {
            // 没有家人，返回空列表
            return memberVoList;
        }

        familyMemberElders.forEach(fme -> {
            MemberVo memberVo = new MemberVo();
            memberVo.setMid(fme.getId().toString());
            memberVo.setMremark(fme.getRemark());
            memberVo.setElderId(fme.getElderId().toString());

            // 获取老人信息
            Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getId, fme.getElderId()));
            memberVo.setName(elder.getName());
            memberVo.setImage(elder.getImage());
            memberVo.setBedNumber(elder.getBedNumber());

            // 根据床号获取房间id,再根据房间id获取房间类型名称
            Long roomId = bedMapper.selectById(elder.getBedId()).getRoomId();
            memberVo.setTypeName(roomMapper.selectById(roomId).getTypeName());

            // 获取IoT设备信息
            Device device = deviceMapper.selectOne(
                    new LambdaQueryWrapper<Device>()
                            .eq(Device::getBindingLocation, elder.getId())
                            .eq(Device::getLocationType, 0)
                                                  );

            if (ObjectUtil.isNotEmpty(device)) {
                memberVo.setIotId(device.getIotId());
                memberVo.setDeviceName(device.getDeviceName());
                memberVo.setProductKey(device.getProductKey());
            }

            memberVoList.add(memberVo);
        });
        return memberVoList;
    }

    /**
     * 获取家人列表(分页）
     *
     * @return 家人列表
     */
    @Override
    public List<MemberVo> listByPage2() {
        return familyMemberElderMapper.listByPage();
    }
}
